﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace pygs.Messaging.Transport
{
    public class WSTransport : CustomTransport
    {
        private WSTransporters _transporters;
        protected WSTransporters transporters { get { return _transporters; } }

        public string URI { get; set; }

        protected override void InitilizeComponent()
        {
            base.InitilizeComponent();
            _transporters = new WSTransporters();
            WSTransportersRegistration.RegisterTransporters(transporters);
        }

        public WSTransport(string URI)
            : base()
        {
            this.URI = URI;
        }

        public WSTransport()
            : base()
        {
        }       

        public override void AssignParams(ComponentParams componentParams)
        {
            this.URI = componentParams.ParamAsString("URI");
        }

        public override bool Send(List<Message> list, out SendingResult result)
        {
            bool success = true;
            result = new SendingResult();
            foreach (var message in list)
            {
                WSCustomTransporter transporter = transporters.GetTransporter(message);
                try
                {
                    if (transporter.Send(message))
                    {
                        result.AddSended(message);
                    }
                    else
                    {
                        success = false;
                        result.AddFailed(message);
                    }
                }
                catch (SendingError e) 
                {
                    success = false;
                    result.AddFailed(message);
                    result.AddError(e);
                };                
            }
            return success;
        }
    }
}
